package com.qsxc.utils;



import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;


import java.util.List;
import java.util.function.BiConsumer;

@Component
public class BatchInsertUtil {
	@Autowired
	@Qualifier(value = "sqlSessionFactory")
	private MybatisSqlSessionFactoryBean factoryBean;

	private static final Logger logger = LoggerFactory.getLogger(BatchInsertUtil.class);

	public <M, T> boolean batchInsert(List<T> list, Class<M> clazz, BiConsumer<M, T> biConsumer) {
		if (list == null || list.size() == 0) {
			return true;
		}
		SqlSessionFactory sqlSessionFactory = null;
		try {
			sqlSessionFactory = factoryBean.getObject();
		} catch (Exception e) {
			logger.error("批量插入失败，获取SqlSessionFactory为空！", e);
			return false;
		}
		SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
		try {
			M mapper = session.getMapper(clazz);
			int i = 0;
			for (T item : list) {
				biConsumer.accept(mapper, item);
				i++;
				if (i % 200 == 0) {
					session.commit();
					session.clearCache();
				}
			}
			session.commit();
			session.clearCache();
		} catch (Exception e) {
			logger.error("BatchInsertUtil batchInsert is exception！clazz={}", clazz.getName(), e);
			session.rollback();
		} finally {
			session.close();
		}
		logger.info("批量插入成功,clazz={},recordCount={}", clazz.getName(), list.size());
		return true;
	}


}
